package com.app.framework.util;

import com.app.config.DCacheConfig;
import com.app.framework.exception.ORMException;
import com.app.framework.orm.StorableModel;
import com.app.framework.orm.util.ClassHelper;
import com.app.store.Store;
import com.app.store.StoreFactory;
import com.app.util.ClassTableUtil;

/**
 * 启动时需要从数据库中读取最大值 设置到redis
 * @author lisong_otd
 *
 */
public class IdxUtil {

	//FIXME 配置文件?
	private static Store store = StoreFactory.newColumnStore();
	
	private static final String CACHE_KEY_PREFIX = "RECORDID|";	
	public static void initId(Class<? extends StorableModel> clz) {
		long max = store.getMaxEntityId(ClassTableUtil.getTableName(clz.getName()));
		store.putOnlyCacheIfAbsent(genCacheKey(clz.getName()), String.valueOf(max));
	}
	public static long nextId(Class<? extends StorableModel> clz) {
		long ret = 0;
		Class<?> tmp = ClassHelper.getRecordClass(clz);
		String cacheKey = genCacheKey(tmp.getName());
		ret = store.increment(cacheKey);
		if(ret < DCacheConfig.getInstance().getTableStartNum()) {
			throw new ORMException("get nextId is error id:"+ret+" cacheKey:"+cacheKey);
		}
		return ret;
	}
	
	private static String genCacheKey(String key) {
		StringBuilder sb = new StringBuilder();
		sb.append(CACHE_KEY_PREFIX);
		sb.append(key);
		return sb.toString();
	}
}
